package blog

import (
	"dustbe/controller/password"
	"dustbe/database"
	"dustbe/util"
	"fmt"
	"net/http"
	"os"
	"strconv"

	"github.com/gin-gonic/gin"
)

func DeleteBlogBySeq(c *gin.Context) {
	deletePassword := c.Query("password")
	if deletePassword != password.MyPasswords.DeleteBlog {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "密码错误（delete）"})
		return
	}
	targetSeq, _ := strconv.Atoi(c.Query("seq"))

	markdownFilePath := fmt.Sprintf("%s/%d.md", blogRoot, targetSeq)
	markdownFilePathExist, _ := util.CheckFilePath(markdownFilePath)
	if markdownFilePathExist {
		err := os.Remove(markdownFilePath)
		if err != nil {
			fmt.Println(err.Error())
			c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "删除失败（删除本地文件失败）"})
			return
		}
	}

	suc, _ := database.DeleteBlogBySeq(targetSeq)
	if !suc {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "删除失败（删除数据库信息失败）"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": "删除成功"})
}
